package wireless.association.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import cm.util.hibernate.HibernateSessionFactory;

import wireless.association.pojo.Association;
import wireless.feature.dao.FeatureDAO;
import wireless.feature.pojo.Feature;

public class AssociationLoad {

	
	private String file;
    private String hql;
    private Query query;
	private Session session;
	
    private Transaction trans;
	
	private List<Association> list = new  ArrayList<Association>();

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public List<Association> getList() {
		return list;
	}

	public void setList(List<Association> list) {
		this.list = list;
	}
	
public String execute() throws Exception {
		
		list = readFileByLines(file);
		
		return "success";
	}
	
	/**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public List<Association> readFileByLines(String fileName) {
        File file = new File(fileName);
        List<Association> list = new ArrayList<Association>();
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 0;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                
                Association association = new Association();
                association.setId(line+1);
                association.setAntecedent(findById(Integer.parseInt(tempString.split(" ")[0])));
                association.setConsequent(findById(Integer.parseInt(tempString.split(" ")[1])));
                list.add(association);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return list;
    }
    
    public String findById(int id){
		
    	session=HibernateSessionFactory.getSession();
		trans=session.beginTransaction();
		String value;
    	hql="select value from Feature where id=:t";
    	query=session.createQuery(hql);
		query.setLong("t",id);//设置查询参数
    	value = query.iterate().next().toString();
    	trans.commit();
    	session.clear();
    	session.close();
    	
    	return value;
    } 
}
